#!/bin/sh

e2e_test_install() {
  kubectl create namespace "$CLUSTER_NAMESPACE"

  deploy_curl_pod "$CLUSTER_NAMESPACE"

  wait_pods_running "$CLUSTER_NAMESPACE" 1
}

e2e_test() {
  run_test "RBAC can-i endpoint should success" check_rbac_success

  run_test "RBAC can-i endpoint should fail" check_rbac_failure

  run_test "RBAC can-i permissions list should success" check_rbac_list
}

get_rbac_status() {
  run_curl -r "stackgres/auth/rbac/can-i/$1/sgclusters?namespace=$CLUSTER_NAMESPACE" -n "$CLUSTER_NAMESPACE" -e "-LI -o /dev/null -w %{http_code}"
}

check_rbac_success() {
  local HTTP_STATUS

  HTTP_STATUS="$(get_rbac_status "get")"

  if [ "$HTTP_STATUS" = "200" ]
  then
    success "rbac can-i endpoint is available"
  else
    fail "rbac can-i endpoint is not available"
  fi
}

check_rbac_failure() {
  local HTTP_STATUS

  kubectl delete clusterrolebinding stackgres-restapi-admin
  kubectl create clusterrolebinding stackgres-restapi-admin --clusterrole=view --user=admin

  HTTP_STATUS="$(get_rbac_status "create")"

  kubectl delete clusterrolebinding stackgres-restapi-admin
  kubectl create clusterrolebinding stackgres-restapi-admin --clusterrole=cluster-admin --user=admin

  if [ "$HTTP_STATUS" = "403" ]
  then
    success "rbac can-i endpoint is available"
  else
    fail "rbac can-i endpoint is not available"
  fi
}

check_rbac_list() {
  local PERMISSIONS_IN_RESPONSE

  PERMISSIONS_IN_RESPONSE="$(run_curl -r "stackgres/auth/rbac/can-i" -n "$CLUSTER_NAMESPACE" -e "-L" \
   | jq --compact-output -M -S '.unnamespaced.namespaces')"

  if [ "$PERMISSIONS_IN_RESPONSE" = '["get","list","create","patch","delete"]' ]
  then
    success "rbac can-i permissions list is available"
  else
    fail "rbac can-i permissions list is not available $PERMISSIONS_IN_RESPONSE"
  fi
}